import { Component } from 'react';
import { AtTag, AtList, AtListItem, AtButton, AtIcon } from 'taro-ui';
import Taro from '@tarojs/taro';
import InputItem from '@/components/InputItem';
import { getServiceDetail } from '@/service/apis/service';
import { View, Text } from '@tarojs/components';
import { globalStore } from '@/store';
import dayjs from 'dayjs';
import { getUserInfo } from '@/service/apis/session/index';
import { createOrder } from '@/service/apis/order';
import { getAppointmentDate, getFirstDay, verifyPhone } from '@/utils/utils';
import { getAddressList } from '@/service/apis/mine/index';
import Radio from '@/components/Radio';
import SelectAddress from '@/subPages/order/component/SelectAddress';
import ServiceItem from '../components/ServiceItem';
import './index.scss';
import TimeModal from '../components/TimeModal';

interface S {
  skuInfo: any;
  serviceInfo: any;
  submitForm: any;
  appointDateMoalShow: boolean;
  currentType: string;
  currentPayType: string;
  visibleAddress: boolean;
  currentUser: any;
  userList: any;
  count: number;
  serviceType: string;
}

function getAppointDate() {
  const currentDay = getFirstDay();
  const time = getAppointmentDate();
  return {
    name: `${dayjs(currentDay).format('YYYY-MM-DD')} ${time.title} ${time.name}`,
    value: `${dayjs(currentDay).format('YYYY-MM-DD')} ${time.value}`,
  };
}

export default class Index extends Component {
  state: S = {
    serviceInfo: {},
    skuInfo: {
      price: 0,
    },
    appointDateMoalShow: false,
    visibleAddress: false,
    currentType: '2',
    currentPayType: '1',
    count: 1,
    currentUser: {},
    userList: [],
    submitForm: {
      time: getAppointDate().name,
      pickup_time: getAppointDate().value,
      username: '',
      phone: '',
      remark: '',
    },
    serviceType: '',
  };
  componentDidMount = async () => {
    const querys: any = Taro.getCurrentInstance().router?.params;
    if (querys?.id && querys?.skuId) {
      this.getServiceDetail(querys.id, querys?.skuId);
    }
    if (querys?.count) {
      this.setState({
        count: querys?.count,
      });
    }
    if (querys?.serviceType === 'shangmen' || querys?.serviceType == 'daodian') {
      this.setState({
        serviceType: querys.serviceType,
        currentType: querys.serviceType === 'shangmen' ? '1' : '2',
      });
    }
    this.getUserInfo();
  };

  componentDidShow() {
    this.getAddressList();
  }

  getUserInfo = async () => {
    try {
      const { data } = await getUserInfo();
      console.log('data', data);
      this.setState({
        submitForm: {
          ...this.state.submitForm,
          phone: data?.user_info?.mobile,
          username: data?.user_info?.username,
        },
      });
    } catch (err) {
      Taro.showToast({
        title: err?.message,
        icon: 'none',
      });
    }
  };

  getAddressList = async () => {
    try {
      const { user_address } = await getAddressList();
      this.setState({
        userList: user_address,
      });
      if (user_address.length > 0) {
        let defaultUser = user_address.filter((item) => item.is_default === 1);
        if (defaultUser.length > 0) {
          this.setState({
            currentUser: defaultUser[0],
          });
        } else {
          this.setState({
            currentUser: user_address[0],
          });
        }
      }
    } catch (err) {
      Taro.showToast({
        title: err?.message,
        icon: 'none',
      });
    }
  };

  getServiceDetail = async (id: string, skuId: string) => {
    try {
      const { data } = await getServiceDetail({
        id,
      });
      if (data.detail) {
        const detail = data.detail;
        const currentSku = detail.product.filter((item) => String(item.id) === skuId)?.[0];
        this.setState({
          serviceInfo: detail,
          skuInfo: {
            id: skuId,
            name: currentSku?.specifications,
            price: currentSku?.vip_price,
            skuText: currentSku?.specifications
          },
        });
        if (detail.cartoon_goods_way.length === 2) return;
        if (detail.cartoon_goods_way[0] === '预约上门') {
          this.setState({
            serviceType: 'shangmen',
            currentType: '1',
          });
        } else {
          this.setState({
            serviceType: 'daodian',
            currentType: '2',
          });
        }
      } else {
        Taro.showToast({
          title: '服务详情数据错误',
          icon: 'none',
        });
      }
    } catch (err) {
      console.log('err: ', err);
      Taro.showToast({
        title: err?.message,
        icon: 'none',
      });
    }
  };

  toResultPage = () => {
    const { submitForm, currentPayType, currentType } = this.state;
    if (!submitForm.username) {
      return Taro.showToast({
        title: '请填写预约人',
        icon: 'none',
      });
    }
    if (!submitForm.phone) {
      return Taro.showToast({
        title: '请填写预约人手机号',
        icon: 'none',
      });
    }
    if (!currentPayType) {
      return Taro.showToast({
        title: '请选择支付方式',
        icon: 'none',
      });
    }
    if (!currentType) {
      return Taro.showToast({
        title: '请选择服务方式',
        icon: 'none',
      });
    }
    if (!verifyPhone(submitForm.phone)) {
      return Taro.showToast({
        title: '请输入正确的手机号',
        icon: 'none',
      });
    }
    this.createOrder();
  };

  openMap = () => {
    const { lat, lng } = globalStore.currentShop;
    Taro.openLocation({
      latitude: lat,
      longitude: lng,
      success: () => {},
    });
  };

  onUserNameChange = (value: string) => {
    this.setState({
      submitForm: {
        ...this.state.submitForm,
        username: value,
      },
    });
  };

  onPhoneChange = (value: string) => {
    this.setState({
      submitForm: {
        ...this.state.submitForm,
        phone: value,
      },
    });
  };

  onRemarkChange = (value: string) => {
    this.setState({
      submitForm: {
        ...this.state.submitForm,
        remark: value,
      },
    });
  };

  setAppointDateModalShow = () => {
    this.setState({
      appointDateMoalShow: true,
    });
  };

  onAppointTimeChange = (time: any) => {
    this.setState({
      submitForm: {
        ...this.state.submitForm,
        time: time.name,
        pickup_time: time.value,
      },
      appointDateMoalShow: false,
    });
  };

  onTypeChange = (value: string) => {
    console.log('value: ', value);
    this.setState({
      currentType: value,
    });
  };

  onPayTypeChange = (value: string) => {
    console.log('value: ', value);
    this.setState({
      currentPayType: value,
    });
  };

  // 创建订单
  createOrder = async () => {
    const querys: any = Taro.getCurrentInstance().router?.params;
    const { submitForm, currentPayType, currentType, currentUser } = this.state;
    const params = {
      ...submitForm,
      address_id: currentType === '1' ? currentUser.id : undefined,
      remark: submitForm.remark || '无',
      id: querys?.id,
      skuId: querys?.skuId,
      serviceType: currentType,
      payType: currentPayType,
      number: querys.count || 1,
    };
    try {
      const { data } = await createOrder(params);
      const orderCode = data.order_sn;
      if (data.pay_config) {
        const { nonceStr, package: packageStr, paySign, signType, timeStamp } = data.pay_config;
        Taro.requestPayment({
          timeStamp,
          nonceStr,
          package: packageStr,
          signType,
          paySign,
          success: (res) => {
            console.log('res: ', res);
            if (res) {
              Taro.redirectTo({
                url: `/subPages/service/result/index?res=1&orderCode=${orderCode}&serviceType=${currentType}`,
              });
            }
          },
          fail: (err) => {
            console.log('err: ', err);
            if (err?.errMsg.indexOf('cancel')) {
              // 用户主动取消支付
              Taro.redirectTo({
                url: `/subPages/service/result/index?res=0&orderCode=${orderCode}&serviceType=${currentType}`,
              });
            } else {
              Taro.redirectTo({
                url: `/subPages/service/result/index?res=2&orderCode=${orderCode}&serviceType=${currentType}`,
              });
            }
          },
        });
      } else {
        if (orderCode) {
          Taro.redirectTo({
            url: `/subPages/service/result/index?res=1&orderCode=${orderCode}&serviceType=${currentType}`,
          });
        }
      }
      console.log('data: ', data);
    } catch (err) {
      Taro.showToast({
        title: err?.message,
        icon: 'none',
      });
    }
  };

  onSelectUser = (user: any) => {
    console.log('user: ', user);
    this.setState({
      currentUser: user,
      visibleAddress: false,
    });
  };

  render() {
    const {
      skuInfo,
      serviceInfo,
      submitForm,
      appointDateMoalShow,
      currentType,
      currentPayType,
      count,
      visibleAddress,
      userList,
      currentUser,
      serviceType,
    } = this.state;
    return (
      <View className="appointment-submit">
        <View className="shop-info" onClick={this.openMap}>
          <View className="shop-name">
            <AtTag type="primary" size="small">
              预约门店
            </AtTag>
            <Text>{serviceInfo.cartoon_store_store_name}</Text>
          </View>
          <View className="shop-address">{serviceInfo.cartoon_store_store_address}</View>
          <View className="iconfont icon-weizhi" />
        </View>
        <View className="section-block">
          <AtList>
            <AtListItem
              title="预约时间"
              extraText={submitForm.time}
              arrow="right"
              onClick={this.setAppointDateModalShow}
            />
            <InputItem
              required
              bordered
              name="username"
              title="* 预约人"
              value={submitForm.username}
              onChange={this.onUserNameChange}
            />
            <InputItem
              required
              name="phone"
              title="* 手机号"
              value={submitForm.phone}
              onChange={this.onPhoneChange}
            />
          </AtList>
        </View>
        <View className="section-block">
          <AtList>
            <AtListItem title="预约服务" />
          </AtList>
          <ServiceItem count={count} service={serviceInfo} skuInfo={skuInfo} />
        </View>
        <View className="section-block service-ways">
          <View className="section-item">
            <View>服务方式</View>
            <View className="service-options">
              {(serviceType === 'daodian' || serviceType === '') && (
                <Radio
                  value="2"
                  checked={currentType === '2'}
                  onChange={() => this.onTypeChange('2')}
                >
                  到店服务
                </Radio>
              )}
              {(serviceType === 'shangmen' || serviceType === '') && (
                <Radio
                  value="1"
                  checked={currentType === '1'}
                  onChange={() => this.onTypeChange('1')}
                >
                  预约上门
                </Radio>
              )}
            </View>
          </View>
        </View>

        <View className="section-block">
          <AtList>
            <AtListItem
              title="服务地址"
              extraText={currentType === '2' ? serviceInfo.cartoon_store_store_address : '用户地址'}
            />
          </AtList>
          {currentType === '1' && (
            <View
              className="shop-info"
              onClick={() => {
                this.setState({
                  visibleAddress: true,
                });
              }}
            >
              {currentUser.address ? (
                <View>
                  <View className="shop-name">
                    <Text>
                      {currentUser.name}-{currentUser.mobile}
                    </Text>
                  </View>
                  <View className="shop-address">
                    {currentUser.province_id}
                    {currentUser.city_id}
                    {currentUser.area_id}
                    {currentUser.addess}
                  </View>
                  <AtIcon value="chevron-right" className="icon-arrow" />
                </View>
              ) : (
                <View>
                  <View className="shop-name">
                    <Text>收货地址</Text>
                  </View>
                  <View className="shop-address">请选择收货地址</View>
                  <AtIcon value="chevron-right" className="icon-arrow" />
                </View>
              )}
            </View>
          )}
        </View>
        <View className="section-block service-ways">
          <View className="section-item">
            <View>支付方式</View>
            <View className="service-options">
              <Radio
                value="1"
                checked={currentPayType === '1'}
                onChange={() => this.onPayTypeChange('1')}
              >
                线下支付
              </Radio>
              <Radio
                value="2"
                checked={currentPayType === '2'}
                onChange={() => this.onPayTypeChange('2')}
              >
                线上支付
              </Radio>
            </View>
          </View>
        </View>
        <View className="card-tips">提示：线下支付支持到驿站或上门服务时刷老年卡</View>
        <View className="section-block">
          <AtList>
            <InputItem
              name="remark"
              title="留言"
              value={submitForm.remark}
              onChange={this.onRemarkChange}
            />
          </AtList>
        </View>
        <View className="bottom-btn">
          <View className="bottom-left">
            <View className="select-title">待支付</View>
            <View className="select-time">￥{(Number(skuInfo.price) * count).toFixed(2)}</View>
          </View>
          <View className="bottom-right">
            <AtButton onClick={this.toResultPage}>提交预约</AtButton>
          </View>
        </View>
        <TimeModal
          currentDate={getFirstDay()}
          currentTime={getAppointmentDate()}
          show={appointDateMoalShow}
          onChange={this.onAppointTimeChange}
          onClose={() => {
            this.setState({
              appointDateMoalShow: false,
            });
          }}
        />
        <SelectAddress
          show={visibleAddress}
          onClose={() => {
            this.setState({
              visibleAddress: false,
            });
          }}
          list={userList}
          onSelect={this.onSelectUser}
        />
      </View>
    );
  }
}
